package net.xju3_4.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.xju3_4.common.framework.simplemvc.RequestMapping;
import net.xju3_4.common.utils.DateUtils;
import net.xju3_4.common.utils.JSONUtil;
import net.xju3_4.common.utils.PageInfo;
import net.xju3_4.common.utils.Result;
import net.xju3_4.entity.OrderEntity;
import net.xju3_4.service.OrderService;
import net.xju3_4.service.impl.OrderServiceImpl;

import java.util.Calendar;
import java.util.Date;

@RequestMapping("/api/order")
public class OrderController {

    OrderService orderService = new OrderServiceImpl();

//  新增订单
@RequestMapping("/insert.do")
public  void orderInsert(HttpServletRequest req, HttpServletResponse resp) {

    OrderEntity order = new OrderEntity();
    try {
        req.setCharacterEncoding("utf-8");
    } catch (java.io.UnsupportedEncodingException e) {
        JSONUtil.printByJSON(resp, Result.fail("字符编码设置失败"));
    }
    order.setCarId(req.getParameter("carId"));
//    order.setUserId(req.getParameter("userId"));
    order.setUserId(Integer.valueOf(req.getParameter("userId")));
    order.setMerchantId(req.getParameter("merchantId"));
    order.setStartTime(DateUtils.parseStr2Date(req.getParameter("startTime")));
    order.setEndTime(DateUtils.parseStr2Date(req.getParameter("endTime")));
    order.setActualStartTime(DateUtils.parseStr2Date(req.getParameter("actualStartTime")));
    order.setActualEndTime(DateUtils.parseStr2Date(req.getParameter("actualEndTime")));
    order.setRentDays(req.getParameter("rentDays"));
    order.setDailyRent(req.getParameter("dailyRent"));
    order.setEstimatedTotalAmount(req.getParameter("estimatedTotalAmount"));
    order.setOvertimeFee(req.getParameter("overtimeFee"));
    order.setDamageFee(req.getParameter("damageFee"));
    order.setFinalAmount(req.getParameter("finalAmount"));
//    order.setStatus(req.getParameter("status"));
    order.setStatus(Integer.valueOf(req.getParameter("status")));
    if (orderService.insert(order)){
        JSONUtil.printByJSON(resp, Result.success(order, "添加成功"));
    }else {
        JSONUtil.printByJSON(resp, Result.fail("添加失败"));
    }
}

//  订单删除
    @RequestMapping("/delete.do")
    public void orderDelete(HttpServletRequest req, HttpServletResponse resp) {
        int id = Integer.parseInt(req.getParameter("id"));
        if (orderService.orderDelete(id)){
            JSONUtil.printByJSON(resp, Result.success("删除成功"));
        }else {
            JSONUtil.printByJSON(resp, Result.fail("删除失败"));
        }

    }
    // 订单修改更新
@RequestMapping("/update.do")
public void orderUpdate(HttpServletRequest req, HttpServletResponse resp) {
    OrderEntity order = new OrderEntity();
    try {
        req.setCharacterEncoding("utf-8");
    } catch (java.io.UnsupportedEncodingException e) {
        JSONUtil.printByJSON(resp, Result.fail("字符编码设置失败"));
        return;
    }

    try {
        // 基础参数设置
        order.setId(Integer.parseInt(req.getParameter("id")));
        order.setCarId(req.getParameter("carId"));
        order.setUserId(Integer.valueOf(req.getParameter("userId")));
        order.setMerchantId(req.getParameter("merchantId"));
        order.setStartTime(DateUtils.parseStr2Date(req.getParameter("startTime")));
        order.setEndTime(DateUtils.parseStr2Date(req.getParameter("endTime")));
        order.setActualStartTime(DateUtils.parseStr2Date(req.getParameter("actualStartTime")));
        order.setActualEndTime(DateUtils.parseStr2Date(req.getParameter("actualEndTime")));
        order.setRentDays(req.getParameter("rentDays"));
        order.setDailyRent(req.getParameter("dailyRent"));
        order.setEstimatedTotalAmount(req.getParameter("estimatedTotalAmount"));
        order.setOvertimeFee(req.getParameter("overtimeFee"));
        order.setDamageFee(req.getParameter("damageFee"));
        order.setStatus(Integer.valueOf(req.getParameter("status")));

        // 处理最终金额计算
        String finalAmountParam = req.getParameter("finalAmount");
            // 获取实际租赁时间和日租金
            Date actualStart = order.getActualStartTime();
            Date actualEnd = order.getActualEndTime();
            String dailyRentStr = order.getDailyRent();
            // 验证必要参数
            if (actualStart != null && actualEnd != null && dailyRentStr != null) {
                try {
                    // 计算实际租赁天数（精确到天）
                    Calendar calStart = Calendar.getInstance();
                    calStart.setTime(actualStart);
                    calStart.set(Calendar.HOUR_OF_DAY, 0);
                    calStart.set(Calendar.MINUTE, 0);
                    calStart.set(Calendar.SECOND, 0);
                    calStart.set(Calendar.MILLISECOND, 0);

                    Calendar calEnd = Calendar.getInstance();
                    calEnd.setTime(actualEnd);
                    calEnd.set(Calendar.HOUR_OF_DAY, 0);
                    calEnd.set(Calendar.MINUTE, 0);
                    calEnd.set(Calendar.SECOND, 0);
                    calEnd.set(Calendar.MILLISECOND, 0);

                    // 计算天数差（忽略小时、分钟、秒）
                    long daysDiff = (calEnd.getTimeInMillis() - calStart.getTimeInMillis()) / (1000 * 60 * 60 * 24);
                    int rentDays = (int) Math.max(1, daysDiff); // 至少1天

                    // 计算最终金额
                    double dailyRent = Double.parseDouble(dailyRentStr);
                    double finalAmount = rentDays * dailyRent;
                    order.setFinalAmount(String.format("%.2f", finalAmount));
                } catch (NumberFormatException e) {
                    JSONUtil.printByJSON(resp, Result.fail("金额计算失败，请检查日租金格式"));
                    return;
                }
            } else {
                JSONUtil.printByJSON(resp, Result.fail("实际租赁时间或日租金不能为空"));
                return;
            }
        // 更新订单
        if (orderService.orderUpdate(order)) {
            JSONUtil.printByJSON(resp, Result.success(order, "修改成功"));
        } else {
            JSONUtil.printByJSON(resp, Result.fail("修改失败"));
        }
    } catch (Exception e) {
        e.printStackTrace();
        JSONUtil.printByJSON(resp, Result.fail("参数解析错误：" + e.getMessage()));
    }
}
//    分页查找
    @RequestMapping("/pageList.do")
    public void orderPageList(HttpServletRequest req, HttpServletResponse resp) {

        OrderEntity order = new OrderEntity();
        try {
            req.setCharacterEncoding("utf-8");
        } catch (java.io.UnsupportedEncodingException e) {
            JSONUtil.printByJSON(resp, Result.fail("字符编码设置失败"));
            return;
        }
        String merchantId = req.getParameter("merchantId");
        String carId = req.getParameter("carId");
        String userId = req.getParameter("userId");
        String status = req.getParameter("status");
        String pageNumStr = req.getParameter("pageNum");

        int pageNum = pageNumStr == null ? 1 : Integer.parseInt(pageNumStr);
        String pageSizeStr = req.getParameter("pageSize");
        int pageSize = pageSizeStr == null ? 10 : Integer.parseInt(pageSizeStr);

        PageInfo<OrderEntity> pageInfo = orderService.orderPageList(carId, userId,status,merchantId, pageNum, pageSize);
        if (pageInfo == null){
            JSONUtil.printByJSON(resp, Result.fail("没有数据"));
        }else{
            JSONUtil.printByJSON(resp, Result.success(pageInfo, "查询成功"));
        }
    }
}
